import React, {Component} from 'react';
import {Alert, Button, Form, Input, Modal, Pagination, Space, Table} from "antd";
import TheButton from "@/components/TheButton";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import { apiGetCouponInfoPage, } from '@/request/coupons';
import { apiAppCouponInfoPage } from '@/request/couponManagement';
import _ from 'lodash';
import moment from 'moment';

class Coupon extends Component {
    constructor(props) {
        super(props)
        this.formRef = React.createRef()
        this.state = {
            isModalShow: false,
            selectedCouponSource: [],
            selectedPageData: {
                pageNo: 1,
                pageSize: 10,
                totalCount: 0,
            },
            searchForm: {
                couponId: '',
                couponTitle:''
            },
            couponList: [],
            couponListPage: {
                pageNo: 1,
                pageSize: 10,
                totalCount: 0,
            },
            dataSourceCopy: [],
            couponTableColumns: [{
                title: '优惠券id',
                dataIndex: 'couponId',
                key: 'couponId',
            },{
                title: '优惠券名称',
                dataIndex: 'couponTitle',
                key: 'couponTitle',
            },{
                title: '优惠券类型',
                dataIndex: 'couponType',
                key: 'couponType',
                render: (text, render) => {
                    let label = ''
                    switch (text) {
                        case "J":
                            label = "代金券"
                            break;
                        case "Z":
                            label = "折扣券"
                            break;
                        default:
                            label = "字段值错误"
                    }
                    return label
                }
            },{
                title: '范围',
                dataIndex: 'commodityScope',
                key: 'commodityScope',
                render: (text, render) => {
                    let label = ''
                    switch (text) {
                        case 0:
                            label = "全部商品可用"
                            break;
                        case 1:
                            label = "限制品类可用"
                            break;
                        case 2:
                            label = "商品券"
                            break;
                        default:
                            label = "字段值错误"
                    }
                    return label
                }
            },{
                title: '优惠',
                dataIndex: "couponPrice",
                key: "couponPrice",
                render: (text, render) => {
                    let label = ''
                    switch (render.couponType) {
                        case 'J':
                            label = "减免"+text/100+"元"
                            break;
                        case 'Z':
                            label = "打"+text+"折"
                            if (render.couponMaxPrice !== -1){
                                label+= ',最大折扣金额'+(render.couponMaxPrice)/100+'元'
                            }
                            break;
                        default:
                            label = "字段值错误"
                    }
                    return label
                }
            },{
                title: '状态',
                dataIndex: "activeStatus",
                key: "activeStatus",
                render: (text, render) => {
                    let label = ''
                    switch (text) {
                        case 0:
                            label = "未开始"
                            break;
                        case 1:
                            label = "进行中"
                            break;
                        case 2:
                            label = "已结束"
                    }
                    return label
                }
            },{
                title: '最近修改时间',
                dataIndex: 'updateTime',
                key: 'updateTime',
                render:(text)=>{
                    return (
                        <>{text?moment(text).format('yyyy-MM-DD HH:mm'):'/'}</>
                    )
                }
            }],
        }
    }
    componentDidMount() {
        this.getData()
    }
    getData = async (value)=>{
        const { pageNo, pageSize } = this.state.couponListPage
        await apiAppCouponInfoPage({pageNo, pageSize, activeStatus:1, over:1, ...value}).then((res)=>{
            console.log(res);
            this.setState({
                couponList: res.rows,
                couponListPage:{
                    pageNo:res.pageNo,
                    pageSize:res.pageSize,
                    totalCount:res.totalCount
                }
            })
        })
    }
    // 选择弹框
    openModal() {
        this.setState({
            isModalShow: true,
            dataSourceCopy: [...this.state.selectedCouponSource]
        }, () => {
            this.getSelectKeys()
            this.resetForm()
        })
    }
    // 选择商品保存
    handleOk = () => {
        this.setState({
            isModalShow: false,
            selectedCouponSource: this.state.dataSourceCopy,
            searchForm: {
                couponId: '',
                couponTitle:''
            }
        },()=>{
            this.props.setData(this.state.selectedCouponSource)
        })
    }
    // 选择商品取消
    handleCancel = () => {
        this.setState({
            isModalShow: false
        })
    }
    // 删除
    del = (record, index)=> {
        const dataSource = [...this.state.selectedCouponSource]
        const {pageNo,pageSize} = this.state.selectedPageData
        dataSource.splice((pageNo-1)*pageSize+index, 1)
        this.setState({
            selectedCouponSource: dataSource
        },()=>{
            this.props.setData(this.state.selectedCouponSource)
        })
    }
    // 获取当前勾选得key
    getSelectKeys() {
        const selectedRowKeys = this.state.dataSourceCopy.map(item => item.couponId)
        this.setState({
            selectedRowKeys
        })
    }
    //批量勾选
    onSelect = (record, selected, selectedRows) => {
        let dataSourceCopy = [...this.state.dataSourceCopy]
        if (selected) {
            dataSourceCopy.push({ ...record })
        } else {
            const delIndex = dataSourceCopy.findIndex(item => item.couponId === record.couponId)
            dataSourceCopy.splice(delIndex, 1)
        }
        this.setState({
            dataSourceCopy
        }, () => this.getSelectKeys())
    }
    // 勾选全部
    onSelectAll = (selected, rows, newRow) => {
        let dataSourceCopy = [...this.state.dataSourceCopy]
        if (selected) {
            dataSourceCopy = dataSourceCopy.concat(...newRow)
        } else {
            const newKeys = newRow.map(item => item.couponId)
            dataSourceCopy = dataSourceCopy.filter(item => !newKeys.includes(item.couponId))
        }
        this.setState({
            dataSourceCopy
        }, () => this.getSelectKeys())
    }
    // 选择内容分页
    selectedPageChange(e) {
        this.state.selectedPageData.pageNo = e
        this.setState({
            selectedPageData: this.state.selectedPageData
        })
    }
    // 弹框分页
    couponListPageChange(e) {
        this.setState({
            couponListPage: {
                pageNo:e,
                pageSize: this.state.couponListPage.pageSize,
                totalCount: this.state.couponListPage.totalCount
            }
        }, () => {
            this.getData()
        })
    }
    // 弹框搜索
    searchGoods() {
        const values = this.formRef.current.getFieldsValue()
        _.forIn(values, (v, k) => {
            if (v === undefined) {
                delete (values[k])
            }
        })
        this.setState({
            searchForm: {
                couponId: values.couponId,
                couponTitle: values.couponTitle
            },
            couponListPage: {
                pageNo: 1,
                pageSize: this.state.couponListPage.pageSize,
                total: 0
            }
        }, () => this.getData(values))
    }
    // 弹框重置
    resetForm() {
        this.formRef.current.resetFields()
        this.setState({
            searchForm: {
                couponId: '',
                couponTitle:''
            },
            couponListPage: {
                pageNo: 1,
                pageSize: 10,
                totalCount: 0,
            },
        }, () => this.getData())
    }
    render() {
        let {
            isModalShow,
            selectedCouponSource,
            selectedPageData,
            couponTableColumns,
            couponList,
            couponListPage,
            selectedRowKeys
        } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onSelect: this.onSelect,
            onSelectAll: this.onSelectAll,
        };
        return (
            <div className='noCanJoinGood'>
                <TheTable dataSource={selectedCouponSource} bordered size="middle"
                       pagination={{
                           showTotal: () => `共${selectedCouponSource.length}条`,
                           pageSize: selectedPageData.pageSize,
                           onChange: (e) => this.selectedPageChange(e)
                       }}
                       columns={[...couponTableColumns,{
                           title: "操作",
                           fixed: "right",
                           width: 200,
                           render: (text, render, index) => {
                               return <TheButton onClick={() => this.del(render, index)}>删除</TheButton>
                           },
                       }]}
                       rowKey={(record) => record.couponId}
                ></TheTable>
                <Modal
                    width={'80%'} title={'选择优惠券'} visible={isModalShow} onOk={this.handleOk} onCancel={this.handleCancel}>
                    <Form layout={'inline'} ref={this.formRef} onFinish={(value) => this.searchGoods(value)} >
                        <Form.Item name="couponId" label='优惠券Id' rules={[{pattern: /^[1-9]*[1-9][0-9]*$/, message:'只允许输入非0开始的数字'}]}>
                            <Input placeholder="优惠券id" style={{ width: 300 }}/>
                        </Form.Item>
                        <Form.Item name="couponTitle" label='优惠券名称'>
                            <Input placeholder="优惠券名称" style={{ width: 300 }}/>
                        </Form.Item>
                        <Form.Item>
                            <Space>
                            <TheButton size="middle" type="primary" htmlType="submit" >查询</TheButton>
                            <TheButton size="middle" type="default" onClick={() => this.resetForm()}>重置</TheButton>
                            </Space>
                        </Form.Item>
                    </Form>
                    <TheTable
                        style={{ margin: '10px 0' }}
                        scroll={{ x: "max-content", y: '57vh' }}
                        columns={couponTableColumns}
                        dataSource={couponList}
                        rowSelection={rowSelection}
                        rowKey={(record) => record.couponId}
                    />
                    <Pagination style={{ textAlign: 'right' }} size="small"
                                current={couponListPage.pageNo}
                                total={couponListPage.totalCount}
                                showSizeChanger={false}
                                onChange={this.couponListPageChange.bind(this)}
                    />
                </Modal>
            </div>
        );
    }
}

export default Coupon;
